#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/5/27 下午2:27
# @Author  : Huang-Bo
import base64
import hashlib
import requests
from utils.logger import setup_logger
from utils.config_loader import load_config

# 初始化配置
config = load_config()
error_logger = setup_logger("error", config["log"]["error_log"], level="ERROR")


class WechatNotifier:
    def __init__(self, webhook_url, upload_url):
        self.webhook_url = webhook_url
        self.upload_url = upload_url

    def send_text_msg(self, msg, cc_to=None):
        """发送文本消息"""
        payload = {
            "msgtype": "text",
            "text": {
                "content": msg,
                "mentioned_mobile_list": cc_to or ["@all"]
            }
        }
        return self._post_message(payload)

    def send_file_msg(self, file_path):
        """发送文件消息"""
        try:
            with open(file_path, 'rb') as f:
                files = {'media': f}
                upload_response = requests.post(self.upload_url, files=files)
                upload_result = upload_response.json()
            if upload_result.get("errcode") != 0:
                print(f"文件上传失败，错误信息：{upload_result.get('errmsg')}")
                return False
            media_id = upload_result.get("media_id")
            payload = {
                "msgtype": "file",
                "file": {
                    "media_id": media_id
                }
            }
            return self._post_message(payload)
        except Exception as e:
            error_logger.error(f"文件发送失败，错误信息：{e}")
            return False

    def send_markdown_msg(self, title, content):
        """发送 Markdown 消息"""
        payload = {
            "msgtype": "markdown",
            "markdown": {
                "title": title,
                "content": content
            }
        }
        return self._post_message(payload)

    def send_image_msg(self, image_path):
        """发送图片消息（base64编码 + md5）"""
        try:
            with open(image_path, 'rb') as f:
                image_data = f.read()
                base64_str = base64.b64encode(image_data).decode('utf-8')
                md5_str = hashlib.md5(image_data).hexdigest()

            payload = {
                "msgtype": "image",
                "image": {
                    "base64": base64_str,
                    "md5": md5_str
                }
            }
            return self._post_message(payload)
        except Exception as e:
            error_logger.error(f"发送图片失败，错误信息：{e}")
            return False

    def _post_message(self, payload):
        """发送POST请求到企业微信"""
        try:
            response = requests.post(self.webhook_url, json=payload)
            result = response.json()
            if result.get("errcode") == 0:
                return True
            else:
                error_logger.error(f"消息发送失败，错误信息：{result.get('errmsg')}")
                return False
        except Exception as e:
            error_logger.error(f"发送企业微信通知时出错：{e}")
            return False
